<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>原生实现列表拖拽</title>
    <style>
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }
      ul {
        margin: 200px auto;
        width: 400px;
        list-style-type: none;
        height: 300px;
        border: 1px solid #eee;
        overflow-y: auto;
      }
      li {
        margin: 5px 0;
        text-align: center;
        width: 100%;
        height: 30px;
        background: skyblue;
        cursor: move;
      }
      .list .moving {
        background: transparent;
        color: transparent;
        border: 1px dashed #ccc;
      }
    </style>
  </head>
  <body>
    <ul class="list">
      <li draggable="true">1</li>
      <li draggable="true">2</li>
      <li draggable="true">3</li>
      <li draggable="true">4</li>
      <li draggable="true">5</li>
      <li draggable="true">6</li>
      <li draggable="true">7</li>
      <li draggable="true">8</li>
      <li draggable="true">9</li>
      <li draggable="true">10</li>
    </ul>

    <script>
      let list = document.querySelector(".list");
      let currentLi;
      list.addEventListener("dragstart", (e) => {
        currentLi = e.target;
      });

      list.addEventListener("dragenter", (e) => {
        e.preventDefault();
        if (e.target === currentLi || e.target === list) {
          return;
        }
        let liArray = Array.from(list.childNodes);
        let currentIndex = liArray.indexOf(currentLi);
        let targetindex = liArray.indexOf(e.target);

        if (currentIndex < targetindex) {
          list.insertBefore(currentLi, e.target.nextElementSibling);
        } else {
          list.insertBefore(currentLi, e.target);
        }
      });
      list.addEventListener("dragover", (e) => {
        e.preventDefault();
      });
      list.addEventListener("dragend", (e) => {
        currentLi.classList.remove("moving");
      });
    </script>
  </body>
</html>
